<template>
  <div>
    <div class="login">
      <div class="fuc">
        <div class="separator"></div>
        <div class="inp">
          <div style="width: 100%; text-align: center; color: black;">
            <h1>登录系统</h1>
          </div>
          <div>
            <div class="login-box">
              <el-form :rules="logRules" status-icon class="login-form" ref="form" :model="form">
                <el-form-item label="用户名" label-width="80px" prop="username">
                  <el-input class="transparent-input" prefix-icon="el-icon-user" v-model="form.username" placeholder="请输入用户名/手机号/邮箱"
                            style="width: 260px"></el-input>
                </el-form-item>
                <el-form-item label="密码" label-width="80px" prop="password">
                  <el-input class="transparent-input" prefix-icon="el-icon-unlock" type="password" style="width: 260px" v-model="form.password"
                            placeholder="请输入密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="验证码" label-width="80px" prop="code">
                  <el-input class="transparent-input" prefix-icon="el-icon-key" v-model="form.code" placeholder="请输入验证码"
                            style="width: 150px"></el-input>
                  <img id="codeImg"  alt="单击图片刷新！" :src="imgURL"
                       @click="changeP" >
                </el-form-item>
                <div class="btns">
                  <el-form-item label="">
                    <el-button type="primary" @click="login">登录</el-button>
                    <el-button type="success" @click="gotoRegister">注册</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="用户注册" :visible.sync="dialogFormVisible" width="500px" center>
      <el-form :rules="registRules" :model="registForm" ref="registForm">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="registForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
          <el-input type="number" min="1" v-model="registForm.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" show-password v-model="registForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="cPassword">
          <el-input type="password" show-password v-model="registForm.cPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="registForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="eMail">
          <el-input v-model="registForm.eMail" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" label-width="80px" prop="code">
          <el-input class="transparent-input" prefix-icon="el-icon-message" v-model="registForm.code" placeholder="请输入4位验证码"  style="width: 170px"></el-input>
          <el-button   type="primary" class="btn-get-code" style="width: 120px" :disabled="countdown > 0"
                       @click="getPhoneCode">{{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}</el-button>
        </el-form-item>
          <el-form-item >
            <div id="registFooter">
              <el-button  @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="success" @click="submitRegist">注 册</el-button>
            </div>
          </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Login",
  data(){
    var validateCode = (rule, value, callback) => {
      var reg = /^\d{4}$/;
      if (!reg.test(value)) {
        callback(new Error('验证码必须为4位数字'));
      }
      //发送请求到后台reids数据库比对验证码
      this.$axios.get('user/checkcode?code='+value+'&phone='+ this.registForm.phone)  //value这个参数就是你输入的验证码:
        .then(resp=>{//服务器正常
          if (!resp.data.flag){//验证码不对，不放行
            callback(new Error(resp.data.msg))
          }else{//手机号已注册且验证码正确,放行
            callback() //放行,验证通过
          }
        })
        .catch(()=>{//服务器异常
          callback(new Error('服务器异常'))
        })
    };
    var validatePhone=(rule,value,callback)=>{
      var phoneRegex = /^[1][3-9]\d{9}$/;
      if(!phoneRegex.test(value)){
        callback(new Error('手机号格式不正确'))
      }
      this.$axios.get('user/checkphone?phone='+value).then(resp=>{
        if (!resp.data){//手机号如果被注册过返回true,反之返回false
          callback(new Error('手机号已经被注册，请直接登录'))
        }else {
          callback()
        }
      })
    };
    var validatePassword=(rule,value,callback)=>{
      if (value!==this.registForm.password){
        callback(new Error('两次输入的密码不一致'))
      }else {
        callback()
      }
    };
    var validateEmail=(rule,value,callback)=>{
      var emailRegex= /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
      if (!emailRegex.test(value)){
        callback(new Error('邮箱格式不正确'))
      }
      this.$axios.get('user/checkemail?email='+value).then(resp=>{
        if (!resp.data){//邮箱如果被注册过返回true,反之返回false
          callback(new Error('此邮箱已经被注册，请直接登录'))
        }else {
          callback()
        }
      })
    }
    return{
      countdown:'',
      rePass:'',
      formLabelWidth: '80px',
      registForm:{
        age: '12',
        phone: '18533949871',
        eMail: '12113@123.com',
        name: '123',
        password: '123123',
        cPassword: '123123'
      },
      dialogFormVisible:false,
      imgURL:'',
      check_code:'',
      form:{
        username: '',
        password: '',
        code:'',
        uuid:'',
      },
      logRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}, /*必须输入:在失去焦点时验证*/
          {min: 3, max: 20, message: '长度在3 到 20 个字符', trigger: 'blur'}, /*长度范围验证:在失去焦点的时候验证*/
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}, /*必须输入:在失去焦点时验证*/
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}, /*长度范围验证:在失去焦点的时候验证*/
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ]
      },
      registRules:{
        name:[
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {max: 6, message: '长度在最长为六个字符', trigger: 'blur'},
        ],
        age:[
          {required: true, message: '请输入年龄', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}, /*必须输入:在失去焦点时验证*/
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}, /*长度范围验证:在失去焦点的时候验证*/
        ],
        cPassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'}, /*必须输入:在失去焦点时验证*/
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}, /*长度范围验证:在失去焦点的时候验证*/
          {validator: validatePassword, trigger: "blur"},
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: validatePhone, trigger: "blur"},
        ],
        eMail:[
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: validateEmail, trigger: "blur"},
        ],
        code:[
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {validator: validateCode, trigger: "blur"},
        ]
      }
    }
  },
  methods:{
    getPhoneCode(){
      var phone =this.registForm.phone
      if (!this.registForm.phone) {
        // 手机号为空，显示提示信息
        this.$message({
          type: 'warning',
          message: '请输入手机号'
        });
        return;
      }
      var phoneRegex = /^[1][3-9]\d{9}$/; // 手机号正则表达式
      if (!phoneRegex.test(this.registForm.phone)) {
        // 手机号不符合要求，显示提示信息
        this.$message({
          type: 'warning',
          message: '请输入正确的手机号'
        });
        return;
      }
      this.$axios.get('user/sendcode?phone='+phone)//value这个参数就是你输入的验证码:
        // console.log(phone)
        .then(resp=>{
          if (resp.data){
            this.$message.success("验证码发送成功，有效期为五分钟")
          }else {
            this.$message.error("系统接口异常")
          }
        })
      this.countdown = 30;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
   submitRegist() {
      console.log("aaa")
      this.$refs.registForm.validate(valid => {
        if (valid) {
          var formData = new FormData;
          formData.append("code", this.registForm.code);
          formData.append("password", this.registForm.password);
          formData.append("age", this.registForm.age);
          formData.append("phone", this.registForm.phone);
          formData.append("eMail", this.registForm.eMail);
          formData.append("name", this.registForm.name);
          this.$axios.post('user/regist',formData).then(resp=>{
            if (resp.data.flag) {
              this.$message.success('注册成功')
            }else {
              alert(resp.data.msg)
            }
          })
        }
      });
    },
    login(){
      this.$refs.form.validate(valid =>{
        if (valid){
          var formData=new FormData
          formData.append("username1",this.form.username)
          formData.append("password",this.form.password)
          formData.append("code",this.form.code)
          formData.append("uuid",this.form.uuid)
          this.$axios.post("/user/verify",formData).then(resp=>{
            if (resp.data.result.flag){
              var user=resp.data.user
              window.sessionStorage.setItem("token",resp.data.result.data)
              // window.sessionStorage.setItem("phone", resp.data.user.phone);
              delete user.password
              delete user.username1
              delete user.delFlag
              delete user.isLock
              window.sessionStorage.setItem("user",JSON.stringify(user));
              // window.sessionStorage.setItem("username", resp.data.user.username);
              // window.sessionStorage.setItem("uid",resp.data.user.id);
              this.$message.success(resp.data.result.msg);
              this.$router.push("/UserView")
            }else {
              this.$message.error(resp.data.result.msg)
            }
          })
        }
      })
    },
    gotoRegister(){
      this.dialogFormVisible=true;
    },
    changeP(){
      /*(this.imgURL='http://localhost:8081/user/kaptcha?d='+new Date()*1).then(resp=>{
        alert(resp.data)
      })*/
      this.$axios.get("/user/kaptcha").then(resp=>{
        this.imgURL = "data:image/png;base64," + resp.data.base64Image;
        this.form.uuid=resp.data.uuid
      })

    },
    check(){
      this.$axios.post("/user/verify?code="+this.check_code).then(resp=>{
        alert(resp.data)
      })
    },
    /**
     * @desc 监听回车键执行事件
     **/
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.login()
      }
    },
  },
  created() {
    this.changeP();
  },
  /**
   * @desc 绑定监听事件
   **/
  mounted() {
    window.addEventListener('keydown', this.keyDown)
  },

  /**
   * @desc 销毁事件
   **/
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false)
  },

}
</script>

<style scoped>
#registFooter{
  position: relative;
  margin-left: 50%;
}
.login {
  position: absolute;
  top: 50%;
  left: 70%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 500px;
  /*background-color: rgba(255, 159, 127, 0.3);*/
  background-color: rgba(0,0,0, 0.2);
  background-size: cover;
  background-image:url("../../assets/mypic/12211.png");
  background-repeat: no-repeat;
  background-position: center;
  box-shadow: 0 0 10px rgba(231, 93, 5, 0.5);
  border-radius: 15px;
  overflow: hidden;
}
.transparent-input{
  opacity: 0.8;
}
#codeImg{
  position: relative;
  top: 10px;
  left: 5px;
}
/*获取验证码*/
/*.code-input {
  position: relative;
}*/

/*.btn-get-code {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}*/

/*.login #asidePic {
  width: 220px;
  height: 100%;

  position: absolute;
  left: 100px;
  top: 20px;

  !* background-color: blueviolet; *!
  !*background-image: url("../../assets/mypic/mainUserPic.jpg");*!
  background-repeat: no-repeat;
  !*background-size: cover;*!
}*/

/*.fuc {
  width: 380px;
  height: 100%;

  position: absolute;
  right: 0;
  top: 0;

  !* background-color: brown; *!
}*/

/*.fuc .pic {
  height: 80px;
  width: 100%;
  line-height: 70px;
  position: absolute;
  top: 25px;
  left: 50%;

  transform: translateX(-50%);
}*/

/*.pic span {
  !* display: inline-block; *!
  padding-top: 10px;
  padding-left: 10px;
  line-height: 70px;
  text-shadow: 0px 0px 8px rgba(231, 104, 20, 0.565);
  font-size: 40px;
  color: #303133;
}*/

/*.pic .Img {
  width: 70px;
  height: 70px;
  border-radius: 50%;

  background-image: url("../../assets/mypic/mainUserPic.jpg");
  background-repeat: no-repeat;
  background-size: cover;

  position: absolute;
  left: 13%;
}*/

.inp {
  position: absolute;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);

  width: 330px;
}
.separator {
  border-left: 1px solid #333; /* 调整颜色为较暗的灰色 */
  height: 100%; /* 调整高度为 20 像素 */
  margin: 0 5px; /* 减小左右边距 */
  transition: height 0.3s ease; /* 添加高度过渡效果 */
}
.centered {
  text-align: center;
  margin-top: 150px;
}
.loginText {
  position: absolute;
  margin-bottom: 10px;
  left: 50%; /* 将文本水平居中 */
  transform: translateX(-50%); /* 水平居中对齐 */
  font-size: 16px; /* 调整字体大小 */
  font-family: Arial, sans-serif; /* 调整字体样式 */
}
.btns {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
